package cn.com.easy.pay.weixinpay.utils;

import java.io.IOException;

import javax.xml.bind.JAXBException;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.BeanUtils;

import cn.com.easy.exception.BusinessException;
import cn.com.easy.pay.weixinpay.config.WeixinPayConfig;
import cn.com.easy.pay.weixinpay.param.UnifiedOrderParam;
import cn.com.easy.pay.weixinpay.param.UnifiedOrderReturnParam;
import cn.com.easy.pay.weixinpay.param.UnifiedOrderUserParam;
import cn.com.easy.utils.HttpClientUtils;
import cn.com.easy.utils.XmlUtils;

/**
 * 微信支付工具类
 * 
 * @author nibili 2017年5月8日
 * 
 */
public class WeixinPayUnifiedOrderUtils {

	/** 统一下单，接口链接 */
	private static String UNIFIED_ODER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";

	/**
	 * 统一下单
	 * 
	 * @param unifiedOrderUserParam
	 * @param weixinPayConfig
	 * @return
	 * @throws Exception
	 * @author nibili 2017年5月8日
	 * @throws BusinessException
	 * @throws IllegalAccessException
	 * @throws JAXBException
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static UnifiedOrderReturnParam doUnifiedOrder(UnifiedOrderUserParam unifiedOrderUserParam, WeixinPayConfig weixinPayConfig) throws BusinessException,
			IllegalAccessException, JAXBException, ClientProtocolException, IOException {

		// 统一下单参数
		UnifiedOrderParam unifiedOrderParam = new UnifiedOrderParam();
		BeanUtils.copyProperties(weixinPayConfig, unifiedOrderParam);
		BeanUtils.copyProperties(unifiedOrderUserParam, unifiedOrderParam);
		// 随机字符串
		String nonce_str = RandomStringUtils.random(16, true, true);
		unifiedOrderParam.setNonce_str(nonce_str);
		// 设置签名字符串
		String sign = Signature.getSign(unifiedOrderParam, weixinPayConfig.getSign_type(), weixinPayConfig.getAppkey());
		unifiedOrderParam.setSign(sign);
		// xml字符串
		String xmlString = XmlUtils.objectToXml(unifiedOrderParam);
		// post请求
		String resultString = HttpClientUtils.post(UNIFIED_ODER_URL, xmlString, null, null);
		if (StringUtils.isBlank(resultString) == true) {
			throw new BusinessException("微信支付统一下单请求结果为空!");
		}
		resultString = new String(resultString.getBytes("ISO-8859-1"), "UTF-8");
		// 结果字符串为xml格式，转成 统一下单 对象
		UnifiedOrderReturnParam unifiedOrderReturnParam = XmlUtils.xmlStrToObject(UnifiedOrderReturnParam.class, resultString);
		return unifiedOrderReturnParam;
	}

}
